package com.yu.service;

import com.yu.domain.Permission;
import com.yu.domain.User;
import com.yu.mapper.PermissionDao;
import com.yu.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: TODO
 * @Author : yu
 * Date : 4/27/2020 5:34 PM
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;
    @Resource
    PermissionDao permissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUserName(username);
        List<Permission> permissions = permissionDao.findByAdminUserId(user.getId());
        Set<SimpleGrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Permission permission : permissions) {
            if (permission!=null&&permission.getName()!=null){
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getName()));
            }
        }
        user.setAuthority(grantedAuthorities);
        return user;
    }
}
